<template>
	<div style="display: flex; justify-content: center; align-items: center;width: 100%;height:100%">
		<!-- 准备一个有宽高的dom ———— 其他内容从父组件传过来 -->
		<div :id="uid" :style="style"></div>
	</div>
</template>
<script setup>
	import {
		ref,
		watch,
		reactive,
		computed,
		onMounted,
		nextTick
	} from 'vue'
	import * as echarts from 'echarts'
	import 'echarts-gl'
	// 引入 ECharts 3D 扩展库
	const props = defineProps({
		dSource: {
			type: Object,
			default: null,
			required: true
		},
		w: {
			type: String,
			default: '100%',
		},
		h: {
			type: String,
			default: '100%',
		}
	})
	const uid = ref('')
	var myChart = null;
	// 时间戳+随机字符
	uid.value = new Date().getTime() + Math.random().toString(32).slice(2, 10)
	//console.log('uid:', uid.value)

	let style = computed(() => ({
		width: props.w,
		height: props.h
	}))
	//console.log('style:', style.value)

	const init = () => {
		if (myChart) {
			myChart.resize();
			myChart.setOption(props.dSource, true); // 强制更新
			return;
		}
		let dom  = document.getElementById(uid.value)
		if(!dom){
			return;
		}
		// 基于准备好的dom，初始化echarts实例
		myChart = echarts.init(dom);
		// 绘制图表
		myChart.setOption(props.dSource)
		window.addEventListener('resize', updateWindowHeight)
	}
	// 深度监听 dSource 变化
	watch(() => props.dSource, (newVal) => {
		console.log("图表数据更新:", newVal);
		nextTick(() => {
			if (myChart) {
				myChart.setOption(newVal, true); // 强制更新
			} else {
				init();
			}
		});
	}, { deep: true });
	const updateWindowHeight = () => {
		// location.reload()
		//console.log('已刷新')
		init();
	}
	defineExpose({
		resize: init,
		clear: () => {
			myChart?.clear();
		}
	})
	onMounted(() => {
		nextTick(() => {
			setTimeout(() => {
				init();
			}, 100);
		})

	})
</script>
<style scoped>

</style>